import { getCartList, updateCartList, delGoods } from "@/api/cart"
export default {
    namespaced: true,
    state() {
        return {
            cartList: [],
            total: null
        }
    },
    getters: {
        //判断是否全部选中
        isAll(state) {
            return state.cartList.every(item => item.isChecked)
        },
        //所有的商品件数
        getTotalNum(state) {
            return state.cartList.reduce((total, cur) => total + cur.goods_num, 0)
        },
        //选中的商品数
        getNum(state) {
            return state.cartList.filter(item => item.isChecked)
        },
        //选中的商品价格
        getPrice(state, getters) {
            return getters.getNum.reduce((total, cur) => total + cur.goods_num * cur.goods.goods_price_max, 0)
        }


    },
    mutations: {
        setCartList(state, data) {
            data.list.forEach(item => item.isChecked = true)
            state.cartList = data.list
            state.total = data.cartTotal
        },
        toggleAll(state, value) {
            state.cartList.forEach(item => item.isChecked = !value);
        }
    },
    actions: {
        async getCartList(context) {
            const { data } = await getCartList()
            context.commit('setCartList', data)
            console.log(data);
        },
        async updateCartList(context, ploay) {
            await updateCartList(ploay.id, ploay.value, ploay.skuId)
        },
        async delGoods(context) {
            await delGoods(context.getters.getNum.map(item => item.goods_id))
            context.dispatch('getCartList')
        }
    }
}